/**
 * 
 */
package com.meetingshow.front.actions;

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;

import nl.captcha.Captcha;
import nl.captcha.Captcha.Builder;
import nl.captcha.text.producer.DefaultTextProducer;
import nl.captcha.text.renderer.DefaultWordRenderer;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.meetingshow.common.Global;
import com.meetingshow.common.MessageCode;
import com.meetingshow.common.base.actions.BaseAction;
import com.meetingshow.common.base.service.model.QueryResults;
import com.meetingshow.common.base.uiservice.exception.BaseUIServiceException;
import com.meetingshow.privilege.uiservice.IUIUserService;
import com.meetingshow.privilege.uiservice.model.UserQueryParasVO;
import com.meetingshow.privilege.uiservice.model.UserVO;
import com.meetingshow.utils.UIServiceFactory;

/**
 * @author louyi
 *
 */
@ParentPackage("json-default")
@Namespace("/login")
public class LoginAction extends BaseAction {

    /**
     * 
     */
    private static final long serialVersionUID = -3779108529283989142L;
    private static final Logger logger = Logger.getLogger(LoginAction.class);
    private static final char[] srcChars = new char[]{'0','1','2','3','4','5','6','7','8','9'};

    private String message;
    private String userName;
    private String password;
    private String captcha;
    
    /**
     * login MeetingShow
     * @return
     */
    @Action(value="login",
            results={
                @Result(type="json", params={"root", "message"})
            }
    )
    public String login() {
        HttpSession session = ServletActionContext.getRequest().getSession();
        //check the CAPTCHA
        if (StringUtils.isBlank(captcha) || session.getAttribute(Global.SESSION_ATTR_CAPTCHA) == null
                || !captcha.equals(session.getAttribute(Global.SESSION_ATTR_CAPTCHA))) {
            message = MessageCode.LOGIN_CAPTCHA_FAIL;
            return SUCCESS;
        }
        
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
            message = MessageCode.LOGIN_USRNAME_PWD_FAIL;
            return SUCCESS;
        }
        UserQueryParasVO userQueryParasVO = new UserQueryParasVO();
        userQueryParasVO.setUserName_e(userName);
        userQueryParasVO.setPassword_e(password);
        
        IUIUserService uiUserService = UIServiceFactory.getUIUserService();
        QueryResults<UserVO> uQueryResults = null;
        try {
            uQueryResults = uiUserService
                    .queryUser(userQueryParasVO);
        } catch (BaseUIServiceException e) {
            logger.error(e);
            message = MessageCode.LOGIN_USRNAME_PWD_FAIL;
            return SUCCESS;
        }
        if (QueryResults.resultsListNotNull(uQueryResults)) {
            UserVO userVO = uQueryResults.getResultList().get(0);
            session.setAttribute(Global.SESSION_ATTR_USER, userVO);
            message = MessageCode.LOGIN_SUCCESS;
        } else {
            message = MessageCode.LOGIN_USRNAME_PWD_FAIL;
            return SUCCESS;
        }
        return SUCCESS;
    }
    
    /**
     * generate captcha
     * @return
     */
    @Action(value="captcha")
    public String captcha() {
        Builder builder = new Captcha.Builder(46, 25);
        List<Font> fontList = new ArrayList<Font>();
        fontList.add(new Font("Courier", Font.BOLD, 18));
        List<Color> colorList = new ArrayList<Color>();
        colorList.add(Color.BLACK);
        DefaultWordRenderer dwr = new DefaultWordRenderer(colorList,fontList);
        builder.addText(new DefaultTextProducer(4, srcChars), dwr);
        Captcha captcha = builder.build();
        ServletActionContext.getRequest().getSession().setAttribute(Global.SESSION_ATTR_CAPTCHA, captcha.getAnswer());
        try {
            ImageIO.write(captcha.getImage(), "JPEG", ServletActionContext.getResponse().getOutputStream());
        } catch (IOException e) {
            logger.error(e);
        }
        return null;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * @return the captcha
     */
    public String getCaptcha() {
        return captcha;
    }

    /**
     * @param captcha the captcha to set
     */
    public void setCaptcha(String captcha) {
        this.captcha = captcha;
    }

    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
    
}
